package day11;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Homework3 {
    static int balance=10000;
    ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
    public void query(){
        rwl.readLock().lock();
     String name= Thread.currentThread().getName();
        System.out.println(name+"查询余额:"+balance);
        rwl.readLock().unlock();
    }
    public void deposit(){
        rwl.writeLock().lock();
        String name= Thread.currentThread().getName();
        System.out.println(name+"开始存款,余额:"+balance);
        Random rand = new Random();
        int r=rand.nextInt(100)+1;
        balance=balance+r;
        System.out.println(name+"存了:"+r+"元");
        rwl.writeLock().unlock();
    }
    public void withdraw(){
        rwl.writeLock().lock();
        String name= Thread.currentThread().getName();
        System.out.println(name+"开始取款,余额:"+balance);
        Random rand = new Random();
        int r=rand.nextInt(100)+1;
        balance=balance-r;
        System.out.println(name+"取了:"+r+"元");
        rwl.writeLock().unlock();
    }

    public static void main(String[] args) {
        Homework3 h = new Homework3();
        while(true){
            new Thread(()->{
            h.query();
            h.deposit();
            h.withdraw();
            },"用户1").start();
            new Thread(()->{
                h.query();
                h.deposit();
                h.withdraw();
            },"用户2").start();
            new Thread(()->{
                h.query();
                h.deposit();
                h.withdraw();
            },"用户3").start();
        }

    }
}
